#include "weather.h"
#include <ESP8266WiFiMulti.h>
#include "Arduino_JSON.h"
#include "wifi.h"
#include "eeconfig.h"

String payload;
WiFiClient pixel_client;
JSONVar weather_obj, weather_obj1;
String weather_img, weather_temp ,weather_temp_day, weather_temp_night;
uint8_t weather_code = 0;
const char get_url[] = "api.seniverse.com";
char get_request[200];
uint8_t force_request = 0;

void weatherTask(void)
{
    static uint16_t cnt = 0;
    if(WIFI_STATE && isVaildChar(*weather_key) && isVaildChar(*weather_city))
    {
        if(cnt%300==0)
        {
            cnt = 0;
            force_request = 0;
            if(!pixel_client.connect(get_url, 80))
            {
                return;
            }
            sprintf(get_request, "GET https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=en&unit=c\n\n", weather_key, weather_city);
            pixel_client.print(get_request);
            payload = pixel_client.readString();
                      
            weather_obj = JSON.parse(payload);
            Serial.println(weather_obj);
            if (JSON.typeof(weather_obj) == "undefined") {
                Serial.println("Parsing input failed!");
                force_request = 1;
                weather_img = "";
                return;
            }
            // pixel_client.stop();
            weather_img = (const char*)(weather_obj["results"][0]["now"]["code"]);
            weather_code = weather_img.toInt();

            weather_temp = (const char*)(weather_obj["results"][0]["now"]["temperature"]);

            // if(!pixel_client.connect(get_url, 80))
            // {
            //     return;
            // }
            memset(get_request, 0, 200);
            sprintf(get_request, 
                    "GET https://api.seniverse.com/v3/weather/daily.json?key=%s&location=%s&language=en&unit=c&start=0&days=1\n\n", 
                    weather_key, weather_city);
            pixel_client.print(get_request);
            payload = pixel_client.readString();
                      
            weather_obj1 = JSON.parse(payload);
            Serial.println(weather_obj1); 
            if (JSON.typeof(weather_obj1) == "undefined") {
                Serial.println("Parsing input failed!");
                force_request = 1;
                weather_img = "";
                return;
            }           
            pixel_client.stop();
            weather_temp_day = (const char*)(weather_obj1["results"][0]["daily"][0]["high"]);
            weather_temp_night = (const char*)(weather_obj1["results"][0]["daily"][0]["low"]);   
        }
        cnt++;
    }
    else
    {
        cnt = 0;
    }
}

